import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getCurrentUser, login, logout as apiLogout } from '../api/auth';

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null);
  // 登录状态
  const isLogin = ref(false);
  // 加载状态
  const loading = ref(false);
  
  // 获取当前用户信息
  const fetchUserInfo = async () => {
    try {
      loading.value = true;
      const token = localStorage.getItem('token');
      
      if (!token) {
        isLogin.value = false;
        userInfo.value = null;
        return null;
      }
      
      const res = await getCurrentUser();
      userInfo.value = res.data;
      isLogin.value = true;
      return res.data;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      userInfo.value = null;
      isLogin.value = false;
      return null;
    } finally {
      loading.value = false;
    }
  };
  
  // 用户登录
  const loginAction = async (loginData) => {
    try {
      loading.value = true;
      const res = await login(loginData);
      
      // 保存token
      localStorage.setItem('token', res.data.tokenValue);
      
      // 获取用户信息
      await fetchUserInfo();
      
      return res;
    } finally {
      loading.value = false;
    }
  };
  
  // 用户登出
  const logoutAction = async () => {
    try {
      loading.value = true;
      await apiLogout();
      
      // 清除token和用户信息
      localStorage.removeItem('token');
      userInfo.value = null;
      isLogin.value = false;
    } finally {
      loading.value = false;
    }
  };
  
  return {
    userInfo,
    isLogin,
    loading,
    fetchUserInfo,
    loginAction,
    logoutAction
  };
}); 